package ext.com.workflow;

import java.io.IOException;
import java.io.Serializable;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import java.util.Locale;
import java.util.Calendar;
import java.sql.Timestamp;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.ReferenceFactory;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleManaged;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.project.Role;
import wt.query.ClassAttribute;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.query.SubSelectExpression;
import wt.session.SessionHelper;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.team.TeamReference;
import wt.team.WTRoleHolder2;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfBlock;
import wt.workflow.engine.WfConnector;
import wt.workflow.engine.WfProcess;
import wt.workflow.work.WorkItem;

import wt.session.SessionServerHelper;

import wt.vc.wip.Workable;

import wt.folder.CabinetBased;

import wt.clients.vc.CheckInOutTaskLogic;

import wt.folder.FolderHelper;

import wt.workflow.engine.WfState;
import wt.query.OrderBy;
import wt.team.TeamHelper;

/**
 *工作流共用程序包
 */
public class WorkflowUtil implements Serializable, RemoteAccess
{

    public static boolean SERVER = true;
    public static String tempDir;
    private static boolean VERBOSE = false;
    public static int ai[] ={ 0 };
    static
    {
        WTProperties props = null;
        try
        {
            props = WTProperties.getLocalProperties();
            tempDir = props.getProperty("wt.temp");
            VERBOSE = props.getProperty("ext.com.workflow.verbose", false);
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    /**
     * 获得对象的相关进程
     *
     * @param obj 需要获取相关进程的对象，该对象可能为WfActivity、WorkItem等，也可能为WfProcess
     * @return 相关进程 <br>
     */
    public static WfProcess getProcess(Object obj)
    {
        if (obj == null)
            return null;

        try
        {
            Persistable persistable = null;

            if (obj instanceof ObjectIdentifier)
            {
                persistable = PersistenceHelper.manager.refresh((ObjectIdentifier) obj);
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    ObjectIdentifier ");
            }
            else if (obj instanceof ObjectReference)
            {
                persistable = ((ObjectReference) obj).getObject();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    ObjectReference ");
            }
            if (obj instanceof Persistable)
            {
                persistable = (Persistable) obj;
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    Persistable ");
            }
            if (persistable instanceof WorkItem)
            {
                persistable = ((WorkItem) persistable).getSource().getObject();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WorkItem ");
            }
            if (persistable instanceof WfActivity)
            {
                persistable = ((WfActivity) persistable).getParentProcess();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfActivity ");
            }
            if (persistable instanceof WfConnector)
            {
                persistable = ((WfConnector) persistable).getParentProcessRef().getObject();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfConnector ");
            }
            if (persistable instanceof WfBlock)
            {
                persistable = ((WfBlock) persistable).getParentProcess();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfBlock ");
            }
            if (persistable instanceof WfProcess)
            {
            	 System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfProcess ");
                return (WfProcess) persistable;
            }
            else
                return null;
        }
        catch (Exception e)
        {
            if (VERBOSE)
            {
                System.out.println("WorkflowUtil.getProcess : error");
                e.printStackTrace();
            }
        }

        return null;
    }
    /**
     *获取流程团队
     * @param process 流程实例
     * @throws WTException
     */
    public static Team getTeam(TeamManaged process) throws WTException
    {
    	System.out.println("@@@@@@@@@@@@@@@@  start 获取流程团队 ");
        return TeamHelper.service.getTeam(process);
    }

    /**
     * 判断某一角色的参与者是否为空
     *
     * @param processObj 工作流本身
     * @param roleName 需要判断的角色
     * @return 若不空，返回真；否则返回假
     * @throws WTException
     */
    public static boolean checkProcessRoleNotEmpty(Object processObj, String roleName) throws WTException
    {
    	System.out.println(" @@@@@@@@@@@ 判断某一角色的参与者是否为空  @@@  start");
        boolean notEmpty = false;
        WfProcess wfprocess = getProcess(processObj);  //获得对象的相关进程
        Team roleHolder = null;
        if (wfprocess != null)
        {
            roleHolder = getTeam(wfprocess); //获取流程团队
            System.out.println("roleHolder @@@@@@@@@@@  "+roleHolder);       
            if (roleHolder != null)
            {
            	System.out.println("111111111");
                Role role = Role.toRole(roleName);
                System.out.println("2222222222222");
                Enumeration principalRefs = roleHolder.getPrincipalTarget(role);
                System.out.println("333333333333333"+principalRefs);
                while (principalRefs != null && principalRefs.hasMoreElements())
                {
                	System.out.println("while 444444");
                    WTPrincipalReference principalRef = (WTPrincipalReference) principalRefs.nextElement();
                    System.out.println("5555555555555555");
                    if (principalRef == null || principalRef.isDisabled())
                        continue;
                    notEmpty = true;
                    System.out.println("@@@@@@@@@ true  =  "+notEmpty);
                    break;
                }
            }
        }
        return notEmpty;
    }

    /**
     * 判断当前用户是否为某一角色参与者
     *
     * @param processObj 工作流本身
     * @param rolename 指定角色
     * @return 若不是，返回false；否则返回true <br>
     */
    public static boolean isProcessRoleParticipant(Object processObj, String rolename)
    {
        if ((processObj == null) || (rolename == null) || (rolename.length() <= 0))
            return false;
        try
        {
            WTPrincipal principal = SessionHelper.manager.getPrincipal();
            System.out.println("WTPrincipal  >>  principal    @@@@ ="+principal.getName());
            WfProcess wfprocess = null;
            wfprocess = getProcess(processObj);//获得对象的相关进程
            if (wfprocess == null)
                throw new WTException("	failed to get the process by process obj " + processObj);
            Enumeration participants = getRoleEnumeration(wfprocess, rolename);
            while (participants.hasMoreElements())
            {
                WTPrincipalReference principalRef = (WTPrincipalReference) participants.nextElement();
                if (principalRef == null || principalRef.isDisabled())
                    continue;
                WTPrincipal participant = principalRef.getPrincipal();
                System.out.println("participant   "+participant.getName());
                if (participant.getName().equals(principal.getName()))
                    return true;
                if (participant instanceof WTGroup)
                {
                    if (((WTGroup) participant).isMember(principal))
                        return true;
                }
            }
        }
        catch (WTException e)
        {
            if (VERBOSE)
            {
                e.printStackTrace();
            }
            return false;
        }
        return false;
    }

    /**
     * 得到流程团队中特定角色的所有参与者信息
     *
     * @param processObj 工作流本身
     * @param roleName 需要获取参与者信息的角色
     * @return 返回一个vector，包含角色的所有参与者（用户和用户组），元素为WTPrincipal类型
     * @throws WTException
     */
    public static Vector getProcessRolePrincipals(Object processObj, String roleName) throws WTException
    {
        Vector PrincipalsV = new Vector();
        if ((processObj == null) || (roleName == null) || (roleName.length() <= 0))
            return PrincipalsV;

        try
        {
            WfProcess process = getProcess(processObj);//获得对象的相关进程
            if (process == null)
                throw new WTException("	failed to get the process by process obj " + processObj);
            Enumeration participants = getRoleEnumeration(process, roleName);
            while (participants.hasMoreElements())
            {
                WTPrincipalReference principalRef = (WTPrincipalReference) participants.nextElement();
                if (principalRef == null || principalRef.isDisabled())
                    continue;
                WTPrincipal participant = principalRef.getPrincipal();
                PrincipalsV.addElement(participant);
            }
        }
        catch (WTException e)
        {
            e.printStackTrace();
            return null;
        }
        return PrincipalsV;
    }

    /**
     * 添加一个参与者到流程的某一指定角色中
     *
     * @param processObj 工作流本身
     * @param rolename 指定角色
     * @param prin 被添加的承担者（用户或用户组）
     * @return 若添加成功，返回true；否则返回false <br>
     */
    public static boolean addPrincipalToProcessRole(Object processObj, String rolename, WTPrincipal prin)
    {
        boolean flag = true;
        WfProcess process = getProcess(processObj);//获得对象的相关进程
        if (process == null)
            return false;

        try
        {
            wt.team.Team team = getTeam(process);
            Enumeration enum1 = getRoleEnumeration(team, rolename);
            while (enum1 != null && enum1.hasMoreElements())
            {
                WTPrincipal wtp = ((WTPrincipalReference) enum1.nextElement()).getPrincipal();
                if (wtp.equals(prin))
                    return false;
            }
            wt.project.Role role = (wt.project.Role) (wt.project.Role.toRole(rolename));
            team.addPrincipal(role, prin);
        }
        catch (Exception e)
        {
            if (VERBOSE)
            {
                System.out.println("WorkflowUtil.addPrincipalToProcessRole : error");
                e.printStackTrace();
            }
            flag = false;
        }
        finally
        {
        }
        return flag;
    }

    /**
     * 添加多个参与者到流程的某一指定角色中
     *
     * @param processObj 工作流本身
     * @param roleName 指定角色
     * @param newPrincipals 被添加的承担者（用户或用户组），一个WTPrincipalReference类型的枚举数组
     * @return 成功添加参与者后的团队
     * @throws WTException
     */
    public static Team addPrincipalsToProcessRole(Object processObj, String roleName, Enumeration newPrincipals) throws WTException
    {
        WfProcess wfprocess = getProcess(processObj);//获得对象的相关进程
        Team team = getTeam(wfprocess);
        team = (Team)addRolePrincipals(team, roleName, newPrincipals);
        return team;
    }

    /**
     * @param teammanaged
     * @param rolename
     * @return 团队角色中的用户集合
     * @throws WTException
     */
    public static Enumeration getRoleEnumeration(wt.team.TeamManaged teammanaged, String rolename) throws WTException
    {
        Team team = getTeam(teammanaged);
        if (team == null)
            return null;
        return getRoleEnumeration(team, rolename);
    }

    /**
     * 从流程的某一指定角色中移除特定用户或用户组
     *
     * @param processObj 工作流进程
     * @param rolename 指定角色
     * @param prin 被移除的承担者（用户或用户组）
     * @return 若移除成功，返回true，否则返回false <br>
     */
    public static boolean removePrincipalFromProcess(Object processObj, String rolename, WTPrincipal prin)
    {
        boolean flag = true;
        WfProcess process = getProcess(processObj);//获得对象的相关进程
        if (process == null)
            return false;

        try
        {
            Role role = (Role) (Role.toRole(rolename));
            Team team = getTeam(process);
            flag= removePrincipalFromTeam(team, rolename, prin);
        }
        catch (Exception e)
        {
            System.out.println("deletePrincipalFromProcess : error");
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }
    
    /**
     *从团队中的某个角色中移除指定的参与者
     * @param team
     * @param rolename
     * @param prin
     * @return
     */
    public static boolean removePrincipalFromTeam(Team team, String rolename, WTPrincipal prin)
    {
        if (prin instanceof WTUser)
        {
            boolean flag = true;

            try
            {
                Role role = (Role) (Role.toRole(rolename));
                team.deletePrincipalTarget(role, prin);
            }
            catch (Exception e)
            {

                System.out.println("WorkflowUtil.deletePrincipalFromTeam : error");
                e.printStackTrace();
                flag = false;
            }

            return flag;
        }
        else if (prin instanceof WTGroup)
        {
            WTGroup group = (WTGroup) prin;
            try
            {
                Enumeration enumeration = group.members();
                while (enumeration.hasMoreElements())
                {
                    WTPrincipal principal = (WTPrincipal) enumeration.nextElement();
                    boolean flag = removePrincipalFromTeam(team, rolename, principal);
                    if (!flag)
                    {
                        return false;
                    }
                }
            }
            catch (WTException e)
            {
                e.printStackTrace();
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 清空流程团队中指定角色的参与者
     * @param processObj 工作流本身
     * @param rolename 指定角色
     * @throws WTException
     */
    public static void clearProcessRole(Object processObj, String rolename) throws WTException
    {
        WfProcess process = getProcess(processObj);//获得对象的相关进程
        Team team= getTeam(process);
        clearTeamRole(team, rolename);
    }
    
    /**
     * 清空流程团队中指定多个角色的参与者
     * @param processObj 工作流本身
     * @param roles 指定角色列表
     * @throws WTException
     */
    public static void clearProcessRoles(Object processObj, Vector roles) throws WTException
    {
        WfProcess process = getProcess(processObj);//获得对象的相关进程
        Team team= getTeam(process);
        for(int i=0; i<roles.size(); i++)
        {
            String rolename=roles.elementAt(i).toString();
            clearTeamRole(team, rolename);
        }
    }
    
    /**
     *清空团队中指定角色的参与者
     * @param team
     * @param rolename
     * @throws WTException
     */
    public static void clearTeamRole(Team team, String rolename) throws WTException
    {
        Enumeration enum1 = getRoleEnumeration(team, rolename);
        while (enum1 != null && enum1.hasMoreElements())
        {
            WTPrincipal wtp = ((WTPrincipalReference) enum1.nextElement()).getPrincipal();
            removePrincipalFromTeam(team, rolename, wtp);
        }
    }

    /**
     * 复制角色参与者
     * @param processObj 工作流本身
     * @param sourceRole 角色源
     * @param destRole 目标角色
     * @throws WTException
     */
    public static void copyProcessRole(Object processObj, String sourceRole, String destRole) throws WTException
    {
        WfProcess wfprocess = getProcess(processObj);//获得对象的相关进程

        Team team = getTeam(wfprocess);
        Enumeration participants = getRoleEnumeration(team, sourceRole);
        if ((participants == null) || (!participants.hasMoreElements()))
            return;
        team = (Team) addRolePrincipals(team, destRole, participants); //向指定团队中某个角色添加多个参与者
    }

    /**
     * 获取团队中指定角色的参与者
     * @param team
     * @param rolename
     * @return 团队角色中的用户集合
     * @throws WTException
     */
    public static Enumeration getRoleEnumeration(wt.team.Team team, String rolename) throws WTException
    {
        Role role = Role.toRole(rolename);
        return team.getPrincipalTarget(role);
    }

    /**
     * 检查指定角色的参与者是否已经存在
     * @param roleHolder
     * @param role
     * @param principal
     * @return 如果存在返回true，否则返回false
     * @throws WTException
     */
    public static boolean hasExistPrincipal(WTRoleHolder2 roleHolder, Role role, WTPrincipal principal) throws WTException
    {
        boolean hasExist = false;

        Enumeration enums = roleHolder.getPrincipalTarget(role);
        while (enums != null && enums.hasMoreElements())
        {
            WTPrincipal aPrincipal = ((WTPrincipalReference) enums.nextElement()).getPrincipal();
            if (aPrincipal.toString().equals(principal.toString()))
            {
                hasExist = true;
                break;
            }
        }
        return hasExist;
    }

    /**
     * 向指定团队中某个角色添加多个参与者
     * @param roleHolder
     * @param roleName
     * @param newPrincipals 新的参与者列表；单个元素值是WTPrincipalReference
     * @return 添加了用户到角色的角色持有者
     * @throws WTException
     */
    public static WTRoleHolder2 addRolePrincipals(WTRoleHolder2 roleHolder, String roleName, Enumeration newPrincipals) throws WTException
    {
        if (roleHolder == null || roleName == null || roleName.length() == 0 || newPrincipals == null || (!newPrincipals.hasMoreElements()))
            return roleHolder;
        Role role = Role.toRole(roleName);
        Enumeration enums = roleHolder.getPrincipalTarget(role);
        // remove the repeated principals
        Vector newPrincipalV = new Vector();
        while (newPrincipals.hasMoreElements())
        {
            newPrincipalV.addElement(newPrincipals.nextElement());
        }
        
        while (enums != null && enums.hasMoreElements())
        {
            WTPrincipalReference principalRef = (WTPrincipalReference) enums.nextElement();
            if (principalRef == null)
                continue;
            Object obj = principalRef.getObject();
            if (obj == null)
                continue;
            newPrincipalV.remove(principalRef);
        }

        for (int i = 0; i < newPrincipalV.size(); i++)
        {
            WTPrincipalReference principalRef = (WTPrincipalReference) newPrincipalV.elementAt(i);
            roleHolder.addPrincipal(role, (WTPrincipal) principalRef.getObject());
        }
        return roleHolder;
    }

    /**
     * 设置对象生命周期状态
     *
     * @param obj 需要设置生命周期状态的对象
     * @param stateStr 被设置的生命周期状态；如果不存在该生命周期状态，则不设置
     * @return 被设置的对象
     * @throws WTException
     */
    public static LifeCycleManaged setLifeCycleState(LifeCycleManaged obj, String stateStr) throws WTException
    {
        State state = State.toState(stateStr);
        if (state.equals(obj.getLifeCycleState()))
            return obj;
        obj = LifeCycleHelper.service.setLifeCycleState(obj, state);

        return obj;
    }

    /**
     * 根据进程，获取相应状态的活动列表 参数completed 为true，获取所有已完成的活动；为false，获取所有未完成的活动。
     *
     * @param process 流程对象
     * @param completed 为true，获取所有已完成的活动；为false，获取所有未完成的活动。
     * @return 　Vector　　元素为WorkItem类型
     * @throws WTException
     */
    public static Vector getWorkItems(WfProcess process, boolean completed) throws WTException
    {
        
        QueryResult workItems;
        QuerySpec qs1 = new QuerySpec();
        qs1.setAdvancedQueryEnabled(true);
        int waaIndex = qs1.appendClassList(wt.workflow.work.WfAssignedActivity.class, false);
        qs1.appendSelectAttribute("thePersistInfo.theObjectIdentifier.id", waaIndex, false);
        qs1.appendWhere(new SearchCondition(wt.workflow.work.WfAssignedActivity.class, "parentProcessRef.key", SearchCondition.EQUAL, getOid(process)));//根据对象获取其ObjectIdentifier类型对象
        SubSelectExpression sse1 = new SubSelectExpression(qs1);
        
        QuerySpec qs2 = new QuerySpec(wt.workflow.work.WorkItem.class);
        qs2.setAdvancedQueryEnabled(true);
        qs2.appendWhere(new SearchCondition(wt.workflow.work.WorkItem.class, "completedBy", !completed), 0);
        ClassAttribute qs2_ca1 = new ClassAttribute(wt.workflow.work.WorkItem.class, "source.key.id");
        qs2.appendAnd();
        SearchCondition qs2_sc2 = new SearchCondition(qs2_ca1, "IN", sse1);
        qs2.appendWhere(qs2_sc2, 0);
        workItems = PersistenceServerHelper.manager.query(qs2);
        return workItems.getObjectVectorIfc().getVector();
        
    }

    /**
     * 根据对象获取其ObjectIdentifier类型对象
     *
     * @param object 对象
     * @return ObjectIdentifier 类型对象
     */
    public static ObjectIdentifier getOid(Object object)
    {
        if (object == null)
        {
            return null;
        }
        if (object instanceof ObjectReference)
        {
            return (ObjectIdentifier) ((ObjectReference) object).getKey();
        }
        else
        {
            return PersistenceHelper.getObjectIdentifier((Persistable) object);
        }
    }

    /**
     * 判断Vector集合中的项是否处于检出状态，Vector中支持的对象类型为WTObject
     *
     * @param reviewObjects 需要判断是否处于检出状态的对象集合
     * @throws WTException
     */
    public static void isObjectCheckedOut(Vector reviewObjects) throws WTException
    {
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        Vector checkedVector = new Vector();
        try
        {
            int partsListSize = reviewObjects.size();
            for (int i = 0; i < partsListSize; i++)
            {
                WTObject wto = (WTObject) reviewObjects.elementAt(i);
                if (VERBOSE)
                {
                    System.out.println("\u5224\u65AD\u5BF9\u8C61\u2018" + wto.getDisplayIdentity() + "\u2019\u662F\u5426\u88AB\u68C0\u51FA\u3002");
                }
                if (isObjectCheckedOut(wto))
                {
                    checkedVector.add(wto);
                }
            }
            if (checkedVector.size() > 0)
            {
                StringBuffer buffer = new StringBuffer();
                for (Iterator iterator = checkedVector.iterator(); iterator.hasNext(); )
                {
                    WTObject wto = (WTObject) iterator.next();
                    buffer.append(wto.getDisplayIdentity()).append("\n");
                }
                throw new WTException("\u5BF9\u8C61\u2018" + buffer.toString() + "\u2019\u6CA1\u6709\u68C0\u5165\u3002");
            }
        }
        catch (WTException e)
        {
            throw e;
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
    }

    /**
     * 判断某一特定对象是否处于检出状态
     *
     * @param wto
     *            需要判断是否处于检出状态的对象
     * <br>
     * <br>
     *             <b>Revision History</b> <br>
     *             <b>Rev:</b> 1.0 - 2009/02/05, Zita Zhang <br>
     *             <b>Comment:</b> Initial release.
     */
    public static boolean isObjectCheckedOut(WTObject wto)
    {
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        try
        {
            if ((wto instanceof Workable) && (wto instanceof CabinetBased) &&
                (CheckInOutTaskLogic.isCheckedOut((Workable) wto) || FolderHelper.inPersonalCabinet((CabinetBased) wto)))
                return true;
            else
                return false;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
        return false;
    }

    /**
     *构造需要判断成员是否为空的角色字符串序列，目前支持10个活动，若实际未达到10个活动，则用“false, null”填补即可
     *该函数应与verifyIfRoleSet函数结合使用
     * @param activity1 活动1是否要走
     * @param roleHey1 活动1参与者角色KEY值
     * @param activity2 活动2是否要走
     * @param roleHey2 活动2参与者角色KEY值
     * @param activity3 活动3是否要走
     * @param roleHey3 活动3参与者角色KEY值
     * @param activity4 活动4是否要走
     * @param roleHey4 活动4参与者角色KEY值
     * @param activity5 活动5是否要走
     * @param roleHey5 活动5参与者角色KEY值
     * @param activity6 活动6是否要走
     * @param roleHey6 活动6参与者角色KEY值
     * @param activity7 活动7是否要走
     * @param roleHey7 活动7参与者角色KEY值
     * @param activity8 活动8是否要走
     * @param roleHey8 活动8参与者角色KEY值
     * @param activity9 活动9是否要走
     * @param roleHey9 活动9参与者角色KEY值
     * @param activity10 活动10是否要走
     * @param roleHey10 活动10参与者角色KEY值
     * @return 所有要走活动参与者角色KEY值+;;;qqq 的集合
     * <br>
     * <br>
     *             <b>Revision History</b> <br>
     *             <b>Rev:</b> 1.0 - 2009/02/05, Zita Zhang <br>
     *             <b>Comment:</b> Initial release.
     */
    public static String getRoleStr(boolean activity1, String roleHey1, boolean activity2, String roleHey2, boolean activity3, String roleHey3, boolean activity4, String roleHey4,
                                    boolean activity5, String roleHey5, boolean activity6, String roleHey6, boolean activity7, String roleHey7, boolean activity8, String roleHey8,
                                    boolean activity9, String roleHey9, boolean activity10, String roleHey10)
    {
        String roleStr = "";
        if (activity1)
        {
            roleStr = roleStr + ";;;qqq" + roleHey1;
        }
        if (activity2)
        {
            roleStr = roleStr + ";;;qqq" + roleHey2;
        }
        if (activity3)
        {
            roleStr = roleStr + ";;;qqq" + roleHey3;
        }
        if (activity4)
        {
            roleStr = roleStr + ";;;qqq" + roleHey4;
        }
        if (activity5)
        {
            roleStr = roleStr + ";;;qqq" + roleHey5;
        }
        if (activity6)
        {
            roleStr = roleStr + ";;;qqq" + roleHey6;
        }
        if (activity7)
        {
            roleStr = roleStr + ";;;qqq" + roleHey7;
        }
        if (activity8)
        {
            roleStr = roleStr + ";;;qqq" + roleHey8;
        }
        if (activity9)
        {
            roleStr = roleStr + ";;;qqq" + roleHey9;
        }
        if (activity10)
        {
            roleStr = roleStr + ";;;qqq" + roleHey10;
        }
        return roleStr;
    }

    /**
     * 判断指定角色集合里的成员是否为空
     * @param processRef 进程实例本身，即self变量
     * @param roles 由函数getRoleStr构造的需要判断参与者的角色集合字符串
     * @throws WTException
     */
    public static void verifyIfProcessRolesSet(ObjectReference processRef, String roles) throws WTException
    {
        WfProcess process= getProcess(processRef);//获得对象的相关进程
        Team team= getTeam(process);
        Role myRole = null;
        if (roles.indexOf(";;;qqq") > -1)
        {
            String roles1[] = roles.split(";;;qqq");
            for (int i = 0; i < roles1.length; i++)
            {
                String role = roles1[i];
                if (role != null && role.length() > 0)
                {
                    myRole = Role.toRole(role);
                    boolean blHasRoleSet = hasTeamRoleSet(team, role);//判断团队角色里的成员是否为空
                    if (!blHasRoleSet)
                    {
                        throw new WTException("\u89D2\u8272\u2018" + myRole.getDisplay() + "\u2019\u6CA1\u6709\u53C2\u4E0E\u8005\uFF0C\u8BF7\u6307\u5B9A\u53C2\u4E0E\u8005\u3002");
                    }
                }
            }

        }
        else
        {
            String role = roles;
            if (role != null && role.length() > 0)
            {
                myRole = Role.toRole(role);
                boolean blHasRoleSet = hasTeamRoleSet(team, role);//判断团队角色里的成员是否为空
                if (blHasRoleSet)
                {
                    return;
                }
                else
                {
                    throw new WTException("\u89D2\u8272\u2018" + myRole.getDisplay() + "\u2019\u6CA1\u6709\u53C2\u4E0E\u8005\uFF0C\u8BF7\u6307\u5B9A\u53C2\u4E0E\u8005\u3002");
                }
            }
        }
    }
    
    /**
     *判断团队角色里的成员是否为空
     * @param team
     * @param role
     * @return
     */
    public static boolean hasTeamRoleSet(Team team, String role)
    {
        Enumeration enumPrin=null;
        try
        {
            Role myRole = null;
            myRole = Role.toRole(role);
            enumPrin = team.getPrincipalTarget(myRole);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return enumPrin.hasMoreElements();
    }

    /**
     * 批量设置对象状态;
     * @param lcmList 需要设置状态的对象集合，支持LifeCycleManaged类型的所有对象
     * @param toState 目标状态，为状态的KEY值
     * @throws WTException
     */
    public static void setLifeCycleState(Vector lcmList, String toState) throws WTException
    {

        int lcmListSize = lcmList.size();

        if (VERBOSE)
            System.out.println("WorkflowUtil.setLifeCycleManagedState： 设置 " + lcmListSize + "个 对象状态为 " + toState);
        boolean flag= SessionServerHelper.manager.setAccessEnforced(false);
        try
        {
            for (int i = 0; i < lcmListSize; i++)
            {
                LifeCycleManaged lcm = (LifeCycleManaged) lcmList.elementAt(i);
                String currentlcmState = lcm.getLifeCycleState().toString();
                if (VERBOSE)
                    System.out.println("    开始设置对象‘" + ((WTObject) lcm).getDisplayIdentifier() + "’的状态. 当前状态：" + currentlcmState);
                lcm = LifeCycleHelper.service.setLifeCycleState(lcm, State.toState(toState));

                if (VERBOSE)
                    System.out.println("    已设置为 " + lcm.getLifeCycleState().toString());
            }
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
    }

    /**
     * 进程启动时复制最近的一个进程实例（相同工作流模板、启动者相同）的团队至本实例
     * 其中，PROMOTER、SUBMITTER角色将不进行复制
     *
     * @param currentProcessObj 本进程实例
     * @param processTemplateName 工作流模板名称
     * @param searchRange 搜索的时间范围，建议值为30，即只搜索30天内的符合要求的进程实例
     * @throws WTException,IOException
     */
    public static void initializeRoleHolderByProcessCreator(Object currentProcessObj, String processTemplateName, int searchRange) throws WTException, IOException
    {
        if (VERBOSE)
            System.out.println(">>>>>>>>>>.initializeRoleHolderByProcessCreator()");

        WfProcess currentProcess = getProcess(currentProcessObj);//获得对象的相关进程
        WTPrincipal curCreator = (WTPrincipal) ((WTPrincipalReference) currentProcess.getCreator()).getObject();

        Team curTeam = getTeam(currentProcess);
        Vector curRoles = curTeam.getRoles();
        if (VERBOSE)
            System.out.println("    the roles of currentProcess=" + curRoles);
        if ((curRoles == null) || (curRoles.size() <= 0))
            return;
        //remove the system roles
        for (int i = 0; i < curRoles.size(); i++)
        {
            Object role = curRoles.elementAt(i);
            if (role.toString().equals("PROMOTER") || role.toString().equals("SUBMITTER"))
            {
                curRoles.removeElementAt(i);
                i--;
            }
        }

        if ((curRoles == null) || (curRoles.size() <= 0))
        {
            if (VERBOSE)
                System.out.println("	remained roles=null, exit!!!");
            return;
        }
        //clear the role's participates
        for (int i = 0; i < curRoles.size(); i++)
        {
            Object role = curRoles.elementAt(i);
            java.util.Enumeration enums = curTeam.getPrincipalTarget(wt.project.Role.toRole(role.toString()));
            if (VERBOSE)
                System.out.println("clear curRole is: " + role);
            while (enums.hasMoreElements())
            {
                wt.org.WTPrincipalReference princ = (wt.org.WTPrincipalReference) (enums.nextElement());
                if (VERBOSE)
                    System.out.println("delete cur Team principal is: " + ((WTPrincipal) (princ.getObject())).getName());
                curTeam.deletePrincipalTarget(wt.project.Role.toRole(role.toString()), (wt.org.WTPrincipal) princ.getObject());
            }

        }
        WTProperties wtproperties = WTProperties.getLocalProperties();

        if (VERBOSE)
            System.out.println("Process searchRange=" + searchRange);

        boolean needUpdate = false;
        ReferenceFactory rf = new ReferenceFactory();
        String curProcessOid = rf.getReferenceString(currentProcess);
        QueryResult enuHistoryProcess = getRecentProcess(processTemplateName, curCreator, searchRange);//根据流程模板名称、启动者、启动时间、运行状态（已执行）等条件搜索符合条件的流程

        while (enuHistoryProcess.hasMoreElements())
        {
            WfProcess historyProcess = (WfProcess) enuHistoryProcess.nextElement();
            if (VERBOSE)
                System.out.println("    get history recently process=" + historyProcess);
            if (curProcessOid.equals(rf.getReferenceString(historyProcess)))
                continue;
            TeamReference tf = (TeamReference) ((TeamManaged) historyProcess).getTeamId();
            if (tf == null)
                continue;

            Team historyTeam = null;
            try
            {
                historyTeam = (Team) (tf.getObject());
            }
            catch (wt.util.WTRuntimeException e)
            {
                System.out.println("error =" + e.toString());
                continue;
            }

            if (historyTeam == null)
                continue;

            Vector historyRoles = historyTeam.getRoles();
            if (VERBOSE)
                System.out.println("    historyProcess(" + historyProcess.getIdentity() + ") team roles=" + historyRoles);
            for (int i = 0; i < curRoles.size(); i++)
            {
                String curRoleName = curRoles.elementAt(i).toString();
                Object curRole = curRoles.elementAt(i);
                java.util.Enumeration enums = historyTeam.getPrincipalTarget(wt.project.Role.toRole(curRole.toString()));
                while (enums.hasMoreElements())
                {
                    wt.org.WTPrincipalReference princ = (wt.org.WTPrincipalReference) (enums.nextElement());
                    if (VERBOSE)
                        System.out.println("add " + ((WTPrincipal) princ.getObject()).getName() + " to curTeam " + curTeam.getName());
                    curTeam.addPrincipal(wt.project.Role.toRole(curRole.toString()), (WTPrincipal) princ.getObject());
                    needUpdate = true;
                }

            }
            if (VERBOSE)
                System.out.println("    needUpdate=" + needUpdate);
            if (needUpdate)
                break;
        }
        if (VERBOSE)
            System.out.println("<<<<<<<<<<<.initializeRoleHolderByProcessCreator()");
    }

    /**
     * 根据流程模板名称、启动者、启动时间、运行状态（已执行）等条件搜索符合条件的流程
     *
     * @param processTemplateName 工作流模板名称
     * @param creator 启动者
     * @param timeRange 搜索的时间范围，单位为天
     * @throws WTException,IOException
     */
    public static QueryResult getRecentProcess(String processTemplateName, WTPrincipal creator, int timeRange) throws WTException
    {
        if (VERBOSE)
            System.out.println("    >>>getRecentProcess()--processs templat name=" + processTemplateName);

        if (creator == null)
        {
            creator = SessionHelper.manager.getPrincipal();
        }
        Locale locale = SessionHelper.manager.getLocale();
        if (VERBOSE)
            System.out.println("    creator=" + creator.getName());
        Calendar calendar = Calendar.getInstance(locale);
        calendar.add(Calendar.DATE, -(timeRange));
        Timestamp timeStamp = new Timestamp(calendar.getTime().getTime());

        QuerySpec querysearch = null;
        QueryResult queryresult = null;
        boolean hasCondition = false;
        querysearch = new QuerySpec(WfProcess.class);
        if (processTemplateName != null && processTemplateName.length() > 0)
        {
            SearchCondition sc5 = new SearchCondition(WfProcess.class, "name", SearchCondition.LIKE, "%" + processTemplateName + "%");
            querysearch.appendWhere(sc5);
            hasCondition = true;
        }

        SearchCondition sc6 = new SearchCondition(WfProcess.class, "creator.key", SearchCondition.LIKE, PersistenceHelper.getObjectIdentifier(creator));
        if (hasCondition)
        {
            querysearch.appendAnd();
        }
        querysearch.appendSearchCondition(sc6);

        SearchCondition sc7 = new SearchCondition(WfProcess.class, "thePersistInfo.createStamp", SearchCondition.GREATER_THAN, timeStamp);
        querysearch.appendAnd();
        querysearch.appendSearchCondition(sc7);

        SearchCondition sc8 = new SearchCondition(WfProcess.class, "state", SearchCondition.LIKE, WfState.CLOSED_COMPLETED_EXECUTED);
        querysearch.appendAnd();
        querysearch.appendSearchCondition(sc8);

        OrderBy orderby = new OrderBy(new ClassAttribute(WfProcess.class, "thePersistInfo.createStamp"), true); //true为降序，false为升序
        querysearch.appendOrderBy(orderby, ai);

        queryresult = PersistenceHelper.manager.find(querysearch);
        return queryresult;
    }

    /**
     *复制本进程实例的团队（即PBO的团队）至随签对象中
     * 其中，PROMOTER、SUBMITTER角色将不进行复制
     *
     * @param processObj 本进程实例self
     * @param batchReviewObj 随签对象集合
     * @throws WTException
     */
    public static void copyRolesToBatchObjects(Object processObj, Vector batchReviewObj) throws WTException
    {
        if (VERBOSE)
            System.out.println("----->.copyRolesToBatchObjects()");
        boolean flag= SessionServerHelper.manager.setAccessEnforced(false);
        try
        {
            WfProcess process = getProcess(processObj);//获得对象的相关进程
            if (VERBOSE)
                System.out.println("get process=" + process);
            
            Team processTeam = getTeam(process);
            
            //设置零部件
            if (batchReviewObj != null && batchReviewObj.size() != 0)
            {
                Enumeration enuBatchReview = batchReviewObj.elements();
                while (enuBatchReview.hasMoreElements())
                {
                    Object destObj= enuBatchReview.nextElement();
                    if(destObj instanceof TeamManaged)
                        copyTeam(processTeam, (TeamManaged)destObj);
                }
            }
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
    }

    /**
     *复制本进程实例的团队（即PBO的团队）至随签对象中
     * 其中，PROMOTER、SUBMITTER角色将不进行复制
     *
     * @param processObj 本进程实例self
     * @param batchReviewObj 随签对象集合
     * @throws WTException
     */
    public static void copyRolesToBatchObjects(Object processObj, WTArrayList batchReviewObj) throws WTException
    {
        if (VERBOSE)
            System.out.println("----->.copyRolesToBatchObjects()");
        boolean flag= SessionServerHelper.manager.setAccessEnforced(false);
        try
        {
            WfProcess process = getProcess(processObj);//获得对象的相关进程
            if (VERBOSE)
                System.out.println("get process=" + process);
            
            Team processTeam = getTeam(process);
            
            //设置零部件
            if (batchReviewObj != null && batchReviewObj.size() != 0)
            {
            	 for (int i = 0; i < batchReviewObj.size(); i++)
                 {
                   Object destObj = batchReviewObj.getPersistable(i);
                   if ((destObj instanceof TeamManaged))
                     copyTeam(processTeam, (TeamManaged)destObj);
                 }
            }
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
    }
    
    /**
     *复制本进程实例的团队（即PBO的团队）至某一个特定对象的团队
     * 其中，PROMOTER、SUBMITTER角色将不进行复制
     * @param processObj 本进程实例self
     * @param destObj 需要复制团队的目标对象，可以是部件/文档/CAD文档
     * @throws WTException
     */
    public static void copyProcessTeam(Object processObj, TeamManaged destObj) throws WTException
    {
        if (VERBOSE)
            System.out.println("--->.copyProcessTeam()");

        WfProcess process = getProcess(processObj);//获得对象的相关进程
        if (VERBOSE)
            System.out.println("get process=" + process);
        Team processTeam = getTeam(process);
        copyTeam(processTeam, destObj);//拷贝团队中的角色参与者;其中，PROMOTER、SUBMITTER角色将不进行复制
    }
    /**
     *拷贝团队中的角色参与者;其中，PROMOTER、SUBMITTER角色将不进行复制
     * @param sourceTeam
     * @param destObj
     * @throws WTException
     */
    public static void copyTeam(Team sourceTeam, TeamManaged destObj) throws WTException
    {
        if (VERBOSE)
            System.out.println("--->.copyTeam()");

        TeamReference teamref = (TeamReference) destObj.getTeamId();
        if (teamref == null)
            return;

        Team destTeam = (Team) (teamref.getObject());
        if (destTeam == null)
            return;

        destTeam = (Team) PersistenceHelper.manager.refresh(destTeam);
        Vector destRoles = destTeam.getRoles();
        if (VERBOSE)
            System.out.println("    the roles of destObj " + destObj + " team=" + destRoles);
        if ((destRoles == null) || (destRoles.size() <= 0))
            return;

        boolean updated = false;
        
        Vector sourceRoles = sourceTeam.getRoles();
        if (VERBOSE)
            System.out.println("    source team(" + sourceTeam.getIdentity() + ") team roles=" + sourceRoles);

        for (int i = 0; i < sourceRoles.size(); i++)
        {
            String srcRoleName = sourceRoles.elementAt(i).toString();
            wt.project.Role role = wt.project.Role.toRole(srcRoleName);
            if (srcRoleName.equals("PROMOTER") || srcRoleName.equals("SUBMITTER"))
            {
                continue;
            }

            //清空团队中参与者
            boolean needRefresh= false;
            Enumeration enums = destTeam.getPrincipalTarget(role);
            while (enums != null && enums.hasMoreElements())
            {
                WTPrincipal principal = ((WTPrincipalReference) enums.nextElement()).getPrincipal();
                destTeam.deletePrincipalTarget(role, principal);
                needRefresh=true;
            }
            if(needRefresh)
                destTeam = (Team) PersistenceHelper.manager.refresh(destTeam);

            Enumeration participants = getRoleEnumeration(sourceTeam, srcRoleName); //获取团队中指定角色的参与者
            if ((participants != null) && participants.hasMoreElements())
            {
                updated = true;
                destTeam = (Team) addRolePrincipals(destTeam, srcRoleName, participants); //向指定团队中某个角色添加多个参与者
            }
        }
        if (VERBOSE)
            System.out.println("  destObj " + destObj + " team updated=" + updated);
    }
    
    public static void main(String[] args) throws Exception
    {
        System.out.println("Begin...");
        System.exit(0);
    }
}
